package com.ruoyi.websocket.utils;


import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

//用来操作WebsocketSession的工具类
@Component
public class WebSocketSessionUtil {

    // key 可以用用户ID、sessionId 等；这里用 sessionId 作为 key
    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //添加session
    public static void addSession(WebSocketSession session) {
        sessions.put(session.getId(), session);
    }

    //移除session
    public static void removeSession(WebSocketSession session) {
        sessions.remove(session.getId());
    }

    //查询当前所有session
    public static Collection<WebSocketSession> getAllSessions() {
        return sessions.values();
    }

    //根据sessionId查询session
    public static WebSocketSession getSession(String sessionId) {
        return sessions.get(sessionId);
    }

    //查询当前在线session数量
    public static int getOnlineCount() {
        return sessions.size();
    }
}
